import { useLayoutEffect } from "react";
import throttle from "lodash/throttle";
import debounce from "lodash/debounce";

var EventEmitter2 = require("eventemitter2");
var emitter = new EventEmitter2();
//自定义拦截器Demo
// function fieldBlurInterceptor() {}
// var cachedEvent = {};

var eventBus = {
  //消息发布
  /**
   *
   * @param {String} topic 消息标识
   * @param  {...any} args 消息内容参数
   */
  publish(topic, ...args) {
    //自定义拦截器Demo
    // if (topic === "field.blur") {
    //   if (cachedEvent[topic + args[0]]!==true) {
    //     cachedEvent[topic + args[0]] = true;
    //     setTimeout(() => {
    //       delete cachedEvent[topic + args[0]];
    //       emitter.emit(topic, ...args);
    //     }, 50);
    //   }
    // }

    emitter.emit(topic, ...args);
  },
  //异步消息发布
  publishAsync(topic, ...args) {
    setTimeout(() => {
      emitter.emit(topic, ...args);
    }, 0);
  },
  //消息订阅
  /**
   *
   * @param {String} topic 消息标识
   * @param {} listener  处理函数
   * @param {Object} config 配置项 节流、防抖
   */
  subscribe(topic, listener, config) {
    if (config?.type === "throttle") {
      //节流
      emitter.on(topic, throttle(listener, config?.wait || 0));
    } else if (config?.type === "debounce") {
      //防抖
      emitter.on(topic, debounce(listener, config?.wait || 0));
    } else {
      emitter.on(topic, listener);
    }
  },
  unSubscribeTopic(topic) {
    emitter.removeAllListeners(topic);
  },
  unSubscribeEvent(topic, listener) {
    emitter.removeListener(topic, listener);
  },
};
//消息订阅hook
/**
 * 
 * @param {String|Array} topic 消息标识|消息标识数组
 * @param {Function} listener 处理函数
 * @param {Array} depends 更新依赖项
 */
function useSubscribe(topic, listener, depends = []) {
  useLayoutEffect(() => {
    if (Array.isArray(topic)) {
      topic.forEach((t) => {
        eventBus.subscribe(t, listener);
      });
    } else if (topic) eventBus.subscribe(topic, listener);
    return () => {
      if (Array.isArray(topic)) {
        topic.forEach((t) => {
          eventBus.unSubscribeEvent(t, listener);
        });
      } else if (topic) eventBus.unSubscribeEvent(topic, listener);
    };
  }, depends);
}

window.eventBus = eventBus;
emitter.setMaxListeners(10000);
export default eventBus;
export { useSubscribe };
